﻿using Jst.Domain.Shared.Enums;
using Newtonsoft.Json;

namespace Jst.Domain.Shared.Models
{
    /// <summary>
    /// 通用API响应结果模型
    /// </summary>
    public class ApiResult
    {
        public int Code { get; set; }
        public string Message { get; set; }

        /// <summary>
        /// 如果data值为null，则忽略序列化将不会返回data字段
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public object Data { get; set; }

        /// <summary>
        /// 初始化一个空API结果
        /// </summary>
        public ApiResult() { }

        /// <summary>
        /// 初始化API结果
        /// </summary>
        public ApiResult(int code, string message) : this(code, message, null) { }

        /// <summary>
        /// 初始化API结果
        /// </summary>
        public ApiResult(int code, string message, object data)
        {
            Code = code;
            Message = message;
            Data = data;
        }

        /// <summary>
        /// 返回成功结果
        /// </summary>
        public static ApiResult Success(object data = null)
        {
            return new ApiResult((int)ResultCode.SUCCESS, "success", data);
        }

        /// <summary>
        /// 返回成功结果
        /// </summary>
        public static ApiResult Success(string message, object data = null)
        {
            return new ApiResult((int)ResultCode.SUCCESS, message, data);
        }

        /// <summary>
        /// 返回错误结果
        /// </summary>
        public static ApiResult Error(ResultCode code, string message)
        {
            return new ApiResult((int)code, message);
        }

        /// <summary>
        /// 返回错误结果
        /// </summary>
        public static ApiResult Error(string message)
        {
            return new ApiResult((int)ResultCode.CUSTOM_ERROR, message);
        }

        /// <summary>
        /// 返回401未授权结果
        /// </summary>
        public static ApiResult Unauthorized()
        {
            return new ApiResult((int)ResultCode.UNAUTHORIZED, "Unauthorized");
        }

        /// <summary>
        /// 返回404未找到结果
        /// </summary>
        public static ApiResult NotFound()
        {
            return new ApiResult((int)ResultCode.NOT_FOUND, "Resource not found");
        }
    }

    /// <summary>
    /// 泛型API响应结果模型
    /// </summary>
    public class ApiResult<T> : ApiResult
    {
        public T Result { get; set; }

        /// <summary>
        /// 初始化泛型API结果
        /// </summary>
        public ApiResult(int code, string message, T data) : base(code, message, data)
        {
            Result = data;
        }

        /// <summary>
        /// 返回成功泛型结果
        /// </summary>
        public static ApiResult<T> Success(T data)
        {
            return new ApiResult<T>((int)ResultCode.SUCCESS, "success", data);
        }
    }
}